package tech.aistar.day11;

import com.sun.org.apache.xpath.internal.functions.FuncTrue;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 本类用来演示:
 * 编写10个线程,t1-计算[1,10]之和,t2->[11,20],....   t10->[91,100],
 * 最后把10个线程的计算结果相加 - result
 *
 * @author: success
 * @date: 2022/8/2 8:43 上午
 */
public class CallableNumDemo implements Callable<Integer> {
    //定义俩个变量
    private int begin;

    private int end;

    public CallableNumDemo(int begin,int end){
        this.begin = begin;
        this.end = end;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;// 每个线程执行的结果
        for (int i = begin; i <= end ; i++) {
            sum+=i;
        }
        return sum;
    }
}
class CallableNumDemoTest{
    public static void main(String[] args) {
        //1. 创建一个FutureTask数组
        FutureTask<Integer>[] futureTask = new FutureTask[10];
        //2. 创建10个线程
        for (int i = 1; i <= 10; i++) {
            Callable c = new CallableNumDemo((i-1)*10+1,i*10);
            futureTask[i-1] = new FutureTask<>(c);
            Thread t = new Thread(futureTask[i-1]);
            t.start();
        }
        Integer result = 0;
        //3. 必须先启动线程,然后才能去调用get()方法
        for (FutureTask<Integer> task : futureTask) {
            try {
                Integer n = task.get();//获取每个线程执行的结果
                result+=n;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.println("计算结果:"+result);
    }
}
